<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="dialogFormVisible = true"
          >新增推销员户头</el-button
        >
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data != null"
        >
          <el-table-column
            prop="name"
            label="姓名"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="phone"
            label="电话"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <!-- <el-table-column prop="content" label="区域" width="auto" align="center" header-align="center">
          </el-table-column> -->
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="Bind(scope.row)"
                >入库绑定</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="detail(scope.row)"
                >推销员详情/编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                style="color: red"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <!-- 新增 -->
      <el-dialog
        title="新增推销员户头"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="姓名:" label-width="100px">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="电话" label-width="100px">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <!-- 
          <el-form-item label="选择区域" label-width="100px">
            <div v-for="(item, index) in form.addresses" :key="index">
              <el-cascader size="large" :options="pcaTextArr" v-model="form.addresses[index]" style="margin-top: 10px">
              </el-cascader>
              <el-button type="warning" style="margin: 10px 0 0 10px" @click="del_addresses(index)">删除</el-button>
            </div>
          </el-form-item> -->
          <!-- <el-button type="primary" style="margin-left: 23%" @click="form.addresses.push({})">新增区域</el-button> -->
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin: 10px 0 0 63%">
          <el-button type="primary" @click="Add">提交</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 详情 -->
      <el-dialog
        title="推销员详情"
        v-model="dialogFormVisible2"
        width="30%"
        :before-close="handleClose"
      >
        <el-form-item label="姓名:" label-width="100px">
          <el-input v-model="Info.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="100px">
          <el-input v-model="Info.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="选择区域" label-width="100px">
          <div v-for="(item, index) in addresses" :key="index">
            <el-cascader size="large" :options="pcaTextArr" v-model="addresses[index]" style="margin-top: 10px">
            </el-cascader>
            <el-button type="warning" style="margin: 10px 0 0 10px" @click="del_addressesinfo(index)">删除</el-button>
          </div>
        </el-form-item>
        <el-button type="primary" style="margin-left: 23%" @click="addresses.push({})">新增区域</el-button> -->
        <div slot="footer" class="dialog-footer" style="margin: 10px 0 0 63%">
          <el-button type="primary" @click="Exit_Add">提交</el-button>
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 入库绑定 -->
      <el-dialog
        title="入库绑定"
        v-model="dialogFormVisible3"
        width="30%"
        :before-close="handleClose"
      >
        <el-form-item label="设备号:" label-width="100px">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入设备编号,并用英文逗号分隔"
            v-model="Bindform.devices"
          ></el-input>
        </el-form-item>
        <div slot="footer" class="dialog-footer" style="margin: 10px 0 0 63%">
          <el-button type="primary" @click="Bind_Add">提交</el-button>
          <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText
} from "element-china-area-data";
import {
  pagedDistributorUsers,
  createDistributorUser,
  updateDistributorUser,
  deleteDistributorUser,
  bindDistributorDevices,
  addDistributorUserAddress,
  updateDistributorUserAddress,
  deleteDistributorUserAddress
} from "@/api/api";
import { tr } from "element-plus/es/locale";
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Salesagent"
});

//新增推销员户头
const dialogFormVisible = ref(false);
const form = reactive({
  name: "",
  phone: "",
  addresses: [{}]
});

// 删除地址
const del_addresses = index => {
  if (form.addresses.length == 1) {
    ElMessage({
      type: "warning",
      message: "必须保留一个区域"
    });
    return;
  } else {
    form.addresses.splice(index, 1);
  }
};
// 提交新增
const Add = () => {
  if (
    form.name === "" &&
    form.phone === ""
    // form.addresses.length === 1 &&
    // Object.keys(form.addresses[0]).length === 0
  ) {
    ElMessage({
      type: "warning",
      message: "请输入全部填写项"
    });
    return; // 如果是原始值，直接返回
  }
  ElMessageBox.confirm("确认新增该推销员吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // form.addresses = form.addresses.map((item, index) => ({
      //   province: item[0],
      //   city: item[1],
      //   county: item[2]
      // }));
      const data = ref({
        name: form.name,
        phone: form.phone
        // addresses: form.addresses
      });
      createDistributorUser(data.value)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: "推销员创建成功"
            });
            dialogFormVisible.value = false;
            GetList();
            form.name = "";
            form.phone = "";
            // form.addresses = [{}];
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
      console.log(form);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消新增"
      });
    });
};

//表格数据
const Data = ref<any>([]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const reply = ref<number>(1); //当前显示
const Searchinfo = ref<any>({
  name: "",
  phone: ""
});
const GetList = () => {
  Data.value = [];
  const data = ref({
    name: Searchinfo.value.name,
    phone: Searchinfo.value.phone,
    pagenumber: currentPage.value,
    pagesize: pageSize.value
  });
  pagedDistributorUsers(data.value)
    .then((res: any) => {
      console.log("表单数据", res);
      Data.value.push(...res.data);
      Total.value = res.total;
    })
    .catch((err: any) => {
      console.log(err);
    });
};

// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

// 详情
const dialogFormVisible2 = ref(false);
const Info = ref<any>("");
const addresses = ref<any>([]);
const del_addressesinfo = index => {
  if (addresses.value.length == 1) {
    ElMessage({
      type: "warning",
      message: "必须保留一个区域"
    });
    return;
  } else {
    addresses.value.splice(index, 1);
  }
};
const detail = (row: any) => {
  dialogFormVisible2.value = true;
  // addresses.value = [];
  Info.value = JSON.parse(JSON.stringify(row));
  // addresses.value = row.addresses.map(item => [
  //   item.province,
  //   item.city,
  //   item.county
  // ]);
  // console.log("详情", Info.value, addresses.value);
};
// 编辑提交
const Exit_Add = () => {
  if (
    Info.value.name === "" &&
    Info.value.phone === ""
    // addresses.value.length === 1 &&
    // Object.keys(addresses.value[0]).length === 0
  ) {
    ElMessage({
      type: "warning",
      message: "请输入全部填写项"
    });
    return; // 如果是原始值，直接返回
  }
  ElMessageBox.confirm("确认该修改吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // Info.value.addresses = addresses.value.map((item, index) => ({
      //   province: item[0],
      //   city: item[1],
      //   county: item[2]
      // }));
      const data = ref({
        id: Info.value.id,
        name: Info.value.name,
        phone: Info.value.phone
        // addresses: Info.value.addresses
      });
      updateDistributorUser(data.value)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: "推销员创建成功"
            });
            dialogFormVisible2.value = false;
            GetList();
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
      console.log(form);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改"
      });
    });
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteDistributorUser(row.id)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: "删除成功"
            });
            GetList();
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

//入库绑定
const dialogFormVisible3 = ref(false);
const Bindform = reactive({
  devices: "",
  distributorid: null
});
const Bind = (row: any) => {
  dialogFormVisible3.value = true;
  Bindform.distributorid = row.id;
};
const Bind_Add = () => {
  if (Bindform.devices === "") {
    ElMessage({
      type: "warning",
      message: "请输入设备编号"
    });
    return; // 如果是原始值，直接返回
  }
  ElMessageBox.confirm("确认绑定这些设备吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const data = Bindform;
      bindDistributorDevices(data)
        .then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: "success",
              message: "绑定成功,请到库存管理页查看"
            });
            dialogFormVisible3.value = false;
            Bindform.devices = "";
          }
        })
        .catch((err: any) => {
          console.log(err);
        });
      console.log(form);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消绑定"
      });
    });
};

//关闭弹窗
const handleClose = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped>
.active-button {
  background-color: #409eff;
  /* 设置按钮激活时的背景颜色 */
  color: white;
  /* 设置按钮激活时的文字颜色 */
}
</style>
